package top.jle.spring.basic.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import top.jle.spring.basic.dto.ImportFallbackDTO;
import top.jle.spring.basic.fis.ImportExcelRowHandler;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

/**
 * @author  jim.lee
 * @date 2022/3/21 17:09
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ExcelUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelUtil.class);
    private static final DataFormatter dataFormatter = new DataFormatter();
    public static void fillErrorMsg(List<ImportFallbackDTO> fallbackDTOList, int sheetNum, int rowNum, String message){
        fallbackDTOList.add(new ImportFallbackDTO(sheetNum,rowNum,message));
    }
    public static String getCellValue(Cell cell){
        return dataFormatter.formatCellValue(cell);
    }

    public static List<ImportFallbackDTO> parseExcel(InputStream inputStream, boolean skipHeader, ImportExcelRowHandler<Row,ImportFallbackDTO> rowHandler){
        List<ImportFallbackDTO> fallbackDTOList = new ArrayList<>();
        try(Workbook workbook = WorkbookFactory.create(inputStream)){
            for(int sheetIndex=0;sheetIndex<workbook.getNumberOfSheets();sheetIndex++){
                Sheet sheet = workbook.getSheetAt(sheetIndex);
                int rowNum = sheet.getPhysicalNumberOfRows();
                if(rowNum==0){
                    LOGGER.info("总行数为0 停止执行");
                    return fallbackDTOList;
                }
                int start = skipHeader?1:0;
                int finalSheetIndex = sheetIndex;
                IntStream.range(start,rowNum).forEach(i-> {
                    LOGGER.info("开始解析行:{}",i);
                    Row row = sheet.getRow(i);
                    ImportFallbackDTO dto = rowHandler.handler(finalSheetIndex,row);
                    if(dto!=null){
                        fallbackDTOList.add(dto);
                    }
                });
            }

        } catch (IOException e) {
            LOGGER.error(e.getMessage(),e);
        }
        return fallbackDTOList;
    }

    public  static <T> Workbook generateExcel(List<List<T>> data,String ...headers) throws IOException {
        Workbook workbook = WorkbookFactory.create(true);
        Sheet sheet = workbook.createSheet();
        int start = 0;
        AtomicInteger colIndex = new AtomicInteger(0);
        if(ArrayUtils.isEmpty(headers)){
            start = 1;
            Row row = sheet.createRow(0);
            Arrays.stream(headers).forEach(header->row.createCell(colIndex.getAndIncrement()).setCellValue(header));
            colIndex.set(0);
        }
        if(CollectionUtils.isNotEmpty(data)){
            AtomicInteger rowIndex = new AtomicInteger(start);
            data.forEach(d->{
                Row row = sheet.createRow(rowIndex.getAndIncrement());
                d.forEach(o->row.createCell(colIndex.getAndIncrement()).setCellValue(o.toString()));
                colIndex.set(0);
            });
        }
        return workbook;


    }

}
